package com.uroboros.spring.guides.rest.order;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

import java.util.ArrayList;
import java.util.List;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;

@Component
public class OrderModelAssembler implements RepresentationModelAssembler<Order, EntityModel<Order>> {

  @Override
  public EntityModel<Order> toModel(Order order) {
    EntityModel<Order> orderEntityModel = EntityModel.of(order,
        linkTo(methodOn(OrderController.class).one(order.getId())).withSelfRel(),
        linkTo(methodOn(OrderController.class).all()).withRel("orders"));

    if (order.getStatus() == Status.IN_PROGRESS) {
      orderEntityModel.add(linkTo(methodOn(OrderController.class).cancel(order.getId())).withRel("cancel"));
      orderEntityModel.add(linkTo(methodOn(OrderController.class).complete(order.getId())).withRel("complete"));
    }

    return orderEntityModel;
  }

  @Override
  public CollectionModel<EntityModel<Order>> toCollectionModel(Iterable<? extends Order> entities) {
    List<EntityModel<Order>> orders = new ArrayList<>();
    entities.forEach(order -> orders.add(toModel(order)));

    return CollectionModel.of(orders, linkTo(methodOn(OrderController.class).all()).withSelfRel());
  }
}
